from django.shortcuts import render,redirect,HttpResponse
from django.core.exceptions import ValidationError

from app02 import models
from app02.utils.encrypt import md5
from app02.utils.pegination import Pegination

# 管理员账户列表
def admin_list(request):
    # 搜索
    data_seach={}
    seach_data = request.GET.get( 'q', '' )
    if seach_data:
        data_seach['user_n__contains']=seach_data

    # 检查用户是否已登录，已登录，继续先下去，未登录，跳转回登录页面
    # 用户发来请求，获取cookie字符串，拿着随机字符串在session中查看有没有
    info = request.session.get( 'info' )
    if not info:
        return redirect( '/login/dl/' )

    # 获取数据库中的全部信息
    data_list=models.Admins.objects.filter(**data_seach)
    #分页
    page_object=Pegination(request,data_list)
    coxtent={
        'data_list':page_object.page_mun,
         'page_string':page_object.html(),
        'seach_data':seach_data
    }
    return render(request,'admin_list.html',coxtent)

#新建管理员
from django import forms
from app02.utils.bootrsap import BootrsapModelForm

#创建ModelForm表单类
class AdminModelForm(BootrsapModelForm):
    # 创建一个字段
    com_password=forms.CharField(
        label='确认密码',
        # 保留原密码的值render_value=True
        widget=forms.PasswordInput(render_value=True)
    )
    class Meta:
        model = models.Admins
        fields=['user_n','password']
        widgets={
           'password':forms.PasswordInput(render_value=True)
        }
    # 给密码加密
    def clean_password(self):
        pwd = self.cleaned_data.get( 'password')
        # 将加密后的密码返回
        return md5(pwd)
    # 钩子函数clean+字段名
    def clean_com_password(self):
        # 获取到验证通过用户输入的确认密码  通过md5()给确认密码加密
        comstf=md5(self.cleaned_data.get('com_password'))
        # 获取到验证通过用户输入密码
        pwd=self.cleaned_data.get('password')
        if comstf != pwd:
            raise ValidationError('密码输入不一致')
        #将com_password的值 返回给cleaned_data  在通过form.save()保存到数据库中
        return comstf

def admin_add(request):
    # 添加管理员
    title='新建管理员'
    if request.method == 'GET':
        form = AdminModelForm()
        return render( request, 'change.html', {'title': title, 'form': form} )
    else:
        form = AdminModelForm( data=request.POST )
        if form.is_valid():
            # print( form.cleaned_data )
            form.save()
            return redirect( '/admins/list/' )
        return render( request, 'change.html', {'title': title, 'form': form} )

# 创建一个编辑的ModelForm类
class AdminEditModelForm(BootrsapModelForm):
    class Meta:
        model = models.Admins
        fields=['user_n']
#编辑管理员
def admin_edit(request,nid):
    #对象/none
    row_object=models.Admins.objects.filter(id=nid).first()
    # 判断id是否为空
    if not row_object:
        return redirect('/admins/list/')

    title='编辑管理员'
    if request.method=='GET':
        form=AdminEditModelForm(instance=row_object)
        return render(request,'change.html',{'title':title,'form':form})
    else:
        form = AdminEditModelForm(data=request.POST,instance=row_object)
        if form.is_valid():
            form.save()
            return redirect('/admins/list/')
        return render( request, 'change.html', {'title': title, 'form': form} )


#删除管理员
def admin_delete(request,nid):
    models.Admins.objects.filter(id=nid).delete()
    return redirect('/admins/list/')


#创建一个重置密码类
class AdminResetModelForm(BootrsapModelForm):
    # 创建一个字段
    com_password=forms.CharField(
        label='确认密码',
        # 保留原密码的值render_value=True
        widget=forms.PasswordInput(render_value=True)
    )
    class Meta:
        model = models.Admins
        fields=['password','com_password']
        widgets={
           'password':forms.PasswordInput(render_value=True)
        }
    # 给密码加密
    def clean_password(self):
        pwd = self.cleaned_data.get( 'password')
        md5_pwd=md5(pwd)
        # 去数据库效验当前密码和输入的密码是否一致   获取对应那一行的id self.instance.pk    .exists()  true/false
        exists =models.Admins.objects.filter(id=self.instance.pk,password=md5_pwd).exists()
        if exists:
            raise ValidationError('输入的密码不能与以前密码相同')
        # 将加密后的密码返回
        return md5_pwd

    # 钩子函数clean+字段名
    def clean_com_password(self):
        # 获取到验证通过用户输入的确认密码  通过md5()给确认密码加密
        comstf=md5(self.cleaned_data.get('com_password'))
        # 获取到验证通过用户输入密码
        pwd=self.cleaned_data.get('password')
        if comstf != pwd:
            raise ValidationError('输入密码与上面不一致')
        #将com_password的值 返回给cleaned_data  在通过form.save()保存到数据库中
        return comstf
#重置密码
def admin_reset(request,nid):
    # 对象/none
    row_object = models.Admins.objects.filter( id=nid ).first()
    # 判断id是否为空
    if not row_object:
        return redirect( '/admins/list/' )
    title='重置密码 - {}'.format(row_object.user_n)
    if request.method=='GET':
        form = AdminResetModelForm()
        return render( request, 'change.html', {'title': title,'form':form} )
    form = AdminResetModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admins/list/')
    return render(request,'change.html', {'title': title, 'form': form})